<template>
  <div class="data-analysis-page">
    <div class="data-analysis-header">
      <a-button type="primary" @click="startConfiguration" :loading="loading">
        数据分析配置
      </a-button>
    </div>

    <!-- 分步弹窗 -->
    <a-modal v-model:visible="stepModalVisible" title="数据分析配置" width="800px" :mask-closable="false" :footer="null"
      :closable="false" class="step-modal">
      <div class="step-container">
        <!-- 步骤指示器 -->
        <a-steps :current="currentStep" class="steps">
          <a-step title="数据选择" />
          <a-step title="滤波器配置" />
          <a-step title="计算参数配置" />
          <!-- <a-step title="FFT分析设置" /> -->
          <a-step title="确认配置" />
        </a-steps>

        <!-- 步骤内容 -->
        <div class="step-content">

          <!-- 第一步: 数据选择 -->
          <div v-show="currentStep === 1" class="step-panel">
            <a-upload :show-file-list="false" :custom-request="handleUpload">
              <template #upload-button>
                <a-button type="primary" shape="round">
                  <template #icon>
                    <icon-upload />
                  </template>
                  <template #default>上传数据</template>
                </a-button>
              </template>
            </a-upload>
            <br>
            <!-- 数据通道信息可视化展示 -->
            <div v-if="state.dataChInfo && state.dataChInfo.length > 0" class="data-channels-container">
              <h3>数据通道信息</h3>
              <div class="data-channels-grid">
                <div 
                  v-for="(channel, index) in state.dataChInfo" 
                  :key="index" 
                  class="channel-card"
                  :class="{ 'channel-card-selected': isChannelSelected(channel) }"
                  @click="selectChannel(channel)"
                >
                  <div class="channel-header">
                    <div class="channel-index">AI {{ channel.index }}</div>
                    <div class="channel-color" :style="{ backgroundColor: getColorFromValue(channel.color) }"></div>
                  </div>
                  <div class="channel-content">
                    <div class="form-row">
                      <label>名称:</label>
                      <div>{{ channel.name || '未命名' }}</div>
                    </div>
                    <div class="form-row">
                      <label>描述:</label>
                      <div>{{ channel.description || '无描述' }}</div>
                    </div>
                    <div class="form-row">
                      <label>单位:</label>
                      <div>{{ channel.unit || '无单位' }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else-if="state.dataUrl && !state.dataChInfo" class="loading-channels">
              <a-spin tip="加载通道信息中..."></a-spin>
            </div>
            <div v-else-if="!state.dataUrl" class="no-data-message">
              请上传数据文件以查看通道信息
            </div>
            
            <!-- 通道和时间区间选择 -->
            <div v-if="state.dataChInfo && state.dataChInfo.length > 0" class="channel-selection-container">
              <h3>分析配置</h3>
              <div class="selection-section">
                <div class="form-row">
                  <label>选择通道:</label>
                  <a-select
                    v-model="state.ch_list"
                    :options="getChannelOptions()"
                    multiple
                    placeholder="请选择要分析的通道"
                    style="width: 100%"
                  ></a-select>
                </div>
                <div class="form-row">
                  <label>时间区间:</label>
                  <div class="time-range-inputs">
                    <a-input-number
                      v-model="state.time_span[0]"
                      :min="0"
                      :max="state.time_span[1]"
                      :precision="3"
                      placeholder="起始时间"
                      style="width: 120px"
                    ></a-input-number>
                    <span class="range-separator">至</span>
                    <a-input-number
                      v-model="state.time_span[1]"
                      :min="state.time_span[0]"
                      :precision="3"
                      placeholder="结束时间"
                      style="width: 120px"
                    ></a-input-number>
                    <span class="unit-label">秒</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 第二步: 滤波器配置 -->
          <div v-show="currentStep === 2" class="step-panel">
            <FilterConfigStep ref="filterStepRef" :initialData="filterConfig"/>
          </div>

          <!-- 第三步: 计算参数配置 -->
          <div v-show="currentStep === 3" class="step-panel">
            <CalculationConfigStep ref="calcStepRef" :initialData="calcConfig" :filterConfig="filterConfig"/>
          </div>

          <!-- 第三步: FFT分析设置 -->
          <!-- <div v-show="currentStep === 3" class="step-panel fft-step-panel">
            <FFTConfigStep ref="fftStepRef" :initialData="fftConfig" @valid="handleStepValid(3, $event)" />
          </div> -->

          <!-- 第四步: 确认配置 -->
          <div v-show="currentStep === 4" class="step-panel">
            <!-- <ReviewConfigStep :filterConfig="filterConfig" :calculationConfig="calcConfig" :fftConfig="fftConfig" /> -->
            <ReviewConfigStep :filterConfig="filterConfig" :calculationConfig="calcConfig" />
          </div>
        </div>

        <!-- 导航按钮 -->
        <div class="step-actions">
          <a-button v-if="currentStep > 1" @click="prevStep" :disabled="loading">
            上一步
          </a-button>

          <a-button v-if="currentStep < 4" type="primary" @click="nextStep" :loading="loading"
            :disabled="!stepsValid[currentStep]">
            下一步
          </a-button>

          <a-button v-if="currentStep === 4" type="primary" @click="submitConfig" :loading="loading">
            完成配置
          </a-button>

          <a-button @click="cancelConfig" :disabled="loading" style="margin-left: 10px">
            取消
          </a-button>
        </div>
      </div>
    </a-modal>

    <div v-if="state.dataIsLoad" class="data-result-container">
      <h2 class="result-title">数据分析结果展示</h2>
      
      <!-- 通道选择器 -->
      <div class="channel-selector">
        <h3><icon-dashboard /> 当前通道:</h3>
        <a-select 
          v-model="state.currentChannelIndex" 
          placeholder="选择通道" 
          style="width: 250px;"
          @change="handleChannelChange"
          allow-search
        >
          <template #prefix>
            <icon-bar-chart />
          </template>
          <a-option 
            v-for="(channelData, index) in state.dataResult" 
            :key="index" 
            :value="index"
          >
            {{ channelData.time_stats[0].channel_name }}
          </a-option>
        </a-select>
      </div>
      <div class="result-content" v-if="currentChannelData">
        <!-- 统计数据展示 - 数值板 -->
        <div class="stats-container">
          <h3>通道统计数据</h3>
          <div class="stats-cards">
            <div 
              class="stat-card" 
              v-for="(key, index) in getStatsKeys()" 
              :key="index"
              @click="switchToChannel(key)"
              :title="getStatCardTitle(key)"
              :class="{'stat-card-highlight': isStatHighlighted(key)}"
            >
              <div class="stat-title">{{ getStatsKeyLabel(key) }}</div>
              <div class="stat-value">{{ formatNumber(currentChannelData.time_stats[0][key]) }}</div>
              <div class="stat-unit">{{ getStatsKeyUnit(key) }}</div>
              <div class="stat-hint">{{ getStatHintText(key) }}</div>
            </div>
          </div>
        </div>

        <!-- 时间特征数据 - 表格 -->
        <div class="features-container">
          <h3>时间块特征数据</h3>
          <a-table 
            :data="currentChannelData.time_features" 
            :bordered="false" 
            :pagination="false" 
            size="small" 
            :scroll="{ x: '100%' }"
            stripe
            :loading="!currentChannelData.time_features"
          >
            <template #columns>
              <a-table-column title="块索引" data-index="block_index" :width="80" fixed="left" align="center" />
              <a-table-column title="开始时间(s)" data-index="block_start" :width="100" align="center" />
              <a-table-column title="结束时间(s)" data-index="block_end" :width="100" align="center" />
              
              <!-- 动态生成表格列 -->
              <template v-for="key in getTableColumns()" :key="key">
                <a-table-column 
                  :title="getStatsKeyLabel(key)" 
                  :data-index="key" 
                  :width="120"
                  align="right"
                >
                  <template #cell="{ record }">
                    <span :class="{'highlight-value': isHighlightValue(record, key)}">
                      {{ formatNumber(record[key]) }}
                    </span>
                  </template>
                </a-table-column>
              </template>
            </template>
          </a-table>
        </div>

        <!-- 结果图片展示 -->
        <div class="result-images">
          <h3>分析结果图表</h3>
          <div class="image-gallery">
            <div 
              v-for="(url, index) in currentChannelData.result_url" 
              :key="index" 
              class="image-container"
              @click="showImagePreview(url, index)"
            >
              <div class="image-title">{{ getImageTitle(index) }}</div>
              <img :src="url" :alt="`分析图表 ${index + 1}`" class="result-image" />
              <div class="image-description">{{ getImageDescription(index) }}</div>
              <div class="image-overlay">
                <span>查看大图</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片预览弹窗 -->
    <a-modal
      v-model:visible="state.imagePreviewVisible"
      :footer="false"
      :mask-closable="true"
      @cancel="state.imagePreviewVisible = false"
      width="90%"
      class="image-preview-modal"
    >
      <div class="preview-container">
        <img :src="state.currentPreviewImage" alt="预览图" class="preview-image" />
        <div class="preview-title">{{ getImageTitle(state.currentPreviewIndex) }}</div>
        <div class="preview-description">{{ getImageDescription(state.currentPreviewIndex) }}</div>
      </div>
      <div class="preview-navigation">
        <a-button 
          type="text" 
          size="large" 
          :disabled="state.currentPreviewIndex <= 0" 
          @click="navigatePreview(-1)"
        >
          <template #icon><icon-left /></template>
        </a-button>
        <span class="preview-counter">{{ state.currentPreviewIndex + 1 }} / {{ currentChannelData?.result_url.length }}</span>
        <a-button 
          type="text" 
          size="large" 
          :disabled="!currentChannelData || state.currentPreviewIndex >= currentChannelData.result_url.length - 1" 
          @click="navigatePreview(1)"
        >
          <template #icon><icon-right /></template>
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { Message, type RequestOption } from '@arco-design/web-vue'
import FilterConfigStep from './FilterConfigStep.vue'
import CalculationConfigStep from './CalculationConfigStep.vue'
// import FFTConfigStep from './FFTConfigStep.vue'
import ReviewConfigStep from './ReviewConfigStep.vue'
import type { FilterConfig, CalculationConfig, FFTSettings } from '@/apis/task/dataAnalysis.ts'
import { uploadFile } from '@/apis'
import { dataReadGetDataChanelList, dataReadAnalysisData } from '@/apis/task/dataRead.ts'

const loading = ref(false)
const stepModalVisible = ref(false)
const currentStep = ref(1)
const stepsValid = reactive([true, true, true, true]) // 各步骤是否有效

interface DataAnalysisReq {

}

// 状态数据
const state = reactive({
  dataUrl: null,
  dataResult: null,
  dataIsLoad: false,
  dataAnalysisReq: null, // 类型 DataAnalysisReq
  dataChInfo: null,
  ch_list: ['AI 1', 'AI 2'],
  time_span: [0, 0.1],
  // 数据结果展示相关
  currentChannelIndex: 0,
  imagePreviewVisible: false,
  currentPreviewImage: '',
  currentPreviewIndex: 0,
})

// 默认统计数据的键名列表
const statsKeys = [
  'mean',
  'max',
  'min',
  'median',
  'kurtosis',
  'variance',
  'skewness',
  'peakToPeak',
  'marginFactor',
  'crestFactor',
  'coeffVariation',
  'RMS'
]

// 动态获取统计数据键名
const getStatsKeys = (): string[] => {
  // 如果有当前通道数据，则从统计数据中提取所有属性
  if (currentChannelData.value && currentChannelData.value.time_stats && currentChannelData.value.time_stats.length > 0) {
    const stats = currentChannelData.value.time_stats[0]
    // 排除不需要显示的属性
    const excludeKeys = ['index', 'channel_name']
    return Object.keys(stats).filter(key => !excludeKeys.includes(key))
  }
  
  // 返回默认键名列表
  return statsKeys
}

// 获取当前选中通道的数据
const currentChannelData = computed(() => {
  if (!state.dataResult || !Array.isArray(state.dataResult) || state.dataResult.length === 0) {
    return null
  }
  return state.dataResult[state.currentChannelIndex]
})

// 处理通道切换事件
const handleChannelChange = (value: number) => {
  state.currentChannelIndex = value
  
  // 滚动到数据结果区域
  setTimeout(() => {
    const resultContainer = document.querySelector('.data-result-container')
    if (resultContainer) {
      resultContainer.scrollIntoView({ behavior: 'smooth' })
    }
  }, 100)
  
  // 显示提示信息
  if (state.dataResult && Array.isArray(state.dataResult) && state.dataResult[value]) {
    const channelName = state.dataResult[value]?.time_stats[0].channel_name || `通道 ${value + 1}`
    Message.success(`已切换到通道: ${channelName}`)
  }
}

// 切换到指定通道的统计数据
const switchToChannel = (key: string) => {
  if (!state.dataResult || !Array.isArray(state.dataResult)) {
    return
  }
  
  // 查找具有最大/最小值的通道
  let maxValue = -Infinity
  let minValue = Infinity
  let targetChannelIndex = 0
  
  state.dataResult.forEach((channelData, index) => {
    if (channelData.time_stats && channelData.time_stats[0][key] !== undefined) {
      const value = channelData.time_stats[0][key]
      
      if (key === 'max' || key === 'peakToPeak' || key === 'RMS' || key === 'variance') {
        // 对于最大值、峰峰值、RMS和方差，查找最大的
        if (value > maxValue) {
          maxValue = value
          targetChannelIndex = index
        }
      } else if (key === 'min') {
        // 对于最小值，查找最小的
        if (value < minValue) {
          minValue = value
          targetChannelIndex = index
        }
      } else if (key === 'kurtosis' || key === 'skewness') {
        // 对于峰度和偏度，查找绝对值最大的
        if (Math.abs(value) > maxValue) {
          maxValue = Math.abs(value)
          targetChannelIndex = index
        }
      } else {
        // 对于其他统计量，查找最大的
        if (value > maxValue) {
          maxValue = value
          targetChannelIndex = index
        }
      }
    }
  })
  
  // 切换到目标通道
  state.currentChannelIndex = targetChannelIndex
  
  // 滚动到数据结果区域
  setTimeout(() => {
    const resultContainer = document.querySelector('.data-result-container')
    if (resultContainer) {
      resultContainer.scrollIntoView({ behavior: 'smooth' })
    }
  }, 100)
  
  // 显示提示信息
  const channelName = state.dataResult[targetChannelIndex]?.time_stats[0].channel_name || `通道 ${targetChannelIndex + 1}`
  const statName = getStatsKeyLabel(key)
  let messageType = key === 'min' ? '最小' : '最大'
  
  // 对于峰度和偏度，显示绝对值最大
  if (key === 'kurtosis' || key === 'skewness') {
    messageType = '绝对值最大'
  }
  
  Message.success(`已切换到${statName}${messageType}的通道: ${channelName}`)
}

// 获取统计数据键名的显示标签
const getStatsKeyLabel = (key: string): string => {
  const labels: Record<string, string> = {
    mean: '平均值',
    max: '最大值',
    min: '最小值',
    median: '中位值',
    kurtosis: '峰度',
    variance: '方差',
    skewness: '偏度',
    peakToPeak: '峰峰值',
    marginFactor: 'Margin factor',
    crestFactor: '波峰因数',
    coeffVariation: 'Coeffcient of Variation',
    RMS: 'RMS'
  }
  return labels[key] || key
}

// 获取统计数据键名的单位
const getStatsKeyUnit = (key: string): string => {
  const units: Record<string, string> = {
    mean: 'V',
    max: 'V',
    min: 'V',
    median: 'V',
    kurtosis: '',
    variance: 'V²',
    skewness: '',
    peakToPeak: 'V',
    marginFactor: '',
    crestFactor: '',
    coeffVariation: '',
    RMS: 'V'
  }
  return units[key] || ''
}

// 获取统计卡片的标题提示
const getStatCardTitle = (key: string): string => {
  const statName = getStatsKeyLabel(key)
  
  if (key === 'min') {
    return `点击查看${statName}最小的通道`
  } else if (key === 'kurtosis' || key === 'skewness') {
    return `点击查看${statName}绝对值最大的通道`
  } else {
    return `点击查看${statName}最大的通道`
  }
}

// 获取统计卡片的提示文本
const getStatHintText = (key: string): string => {
  if (key === 'min') {
    return '点击查看最小值通道'
  } else if (key === 'kurtosis' || key === 'skewness') {
    return '点击查看绝对值最大通道'
  } else if (key === 'variance' || key === 'RMS' || key === 'peakToPeak') {
    return '点击查看最大值通道'
  } else if (key === 'marginFactor' || key === 'crestFactor' || key === 'coeffVariation') {
    return '点击查看特征因子通道'
  } else {
    return '点击查看最值通道'
  }
}

// 格式化数字显示
const formatNumber = (value: number): string => {
  if (value === undefined || value === null) {
    return '-'
  }
  
  // 科学计数法显示小数
  if (Math.abs(value) < 0.001 || Math.abs(value) > 10000) {
    return value.toExponential(6)
  }
  
  // 常规显示，保留6位小数
  return value.toFixed(6)
}

// 显示图片预览
const showImagePreview = (url: string, index: number) => {
  state.currentPreviewImage = url
  state.currentPreviewIndex = index
  state.imagePreviewVisible = true
}

// 预览图片导航
const navigatePreview = (direction: number) => {
  if (!currentChannelData.value || !currentChannelData.value.result_url) {
    return
  }
  
  const newIndex = state.currentPreviewIndex + direction
  if (newIndex >= 0 && newIndex < currentChannelData.value.result_url.length) {
    state.currentPreviewIndex = newIndex
    state.currentPreviewImage = currentChannelData.value.result_url[newIndex]
  }
}

// 获取图片标题
const getImageTitle = (index: number): string => {
  const titles = [
    '时域分析图',
    '获取时域信号波形图',
    '时域统计量柱状图',
    '频域主频对比图',
    '频域功率谱密度图',
    'STFT 时频图',
    '小波能量分布',
  ]
  return titles[index % titles.length] || `分析图表 ${index + 1}`
}

// 获取图片描述
const getImageDescription = (index: number): string => {
  const descriptions = [
    '展示信号在时域中的整体特征，包括波形和变化趋势',
    '直观呈现时域信号的波形形态，便于观察信号的幅值随时间的变化',
    '通过柱状图展示时域信号的关键统计量（如均值、方差等）分布情况',
    '对比不同信号或同一信号在不同条件下的频域主频分布差异',
    '显示信号在频域中的功率分布，反映各频率成分的能量集中程度',
    '通过短时傅里叶变换展示信号的时变频率特性，揭示时间-频率关联关系',
    '利用小波变换分析信号在不同频率和时间区域的能量分布特征',
  ]
  return descriptions[index % descriptions.length] || `图表 ${index + 1} 的详细分析结果`
}

// 获取表格列
const getTableColumns = (): string[] => {
  // 如果有当前通道数据，则从第一个时间特征数据中提取所有属性
  if (currentChannelData.value && currentChannelData.value.time_features && currentChannelData.value.time_features.length > 0) {
    const firstFeature = currentChannelData.value.time_features[0]
    // 排除固定列和不需要显示的属性
    const excludeKeys = ['index', 'channel_name', 'block_index', 'block_start', 'block_end']
    return Object.keys(firstFeature).filter(key => !excludeKeys.includes(key))
  }
  
  // 默认列
  return [
    'max',
    'min',
    'mean',
    'peakToPeak',
    'RMS',
    'variance',
    'skewness',
    'kurtosis',
    'median',
    'crestFactor',
    'marginFactor',
    'coeffVariation'
  ]
}

// 判断是否需要高亮显示值
const isHighlightValue = (record: any, key: string): boolean => {
  if (!record || record[key] === undefined) return false
  
  // 获取当前列的所有值
  const allValues = currentChannelData.value?.time_features.map(item => item[key]) || []
  
  // 找出最大值和最小值
  const maxValue = Math.max(...allValues.filter(v => v !== undefined && v !== null))
  const minValue = Math.min(...allValues.filter(v => v !== undefined && v !== null))
  
  // 根据不同的统计量类型，决定高亮最大值还是最小值
  if (key === 'min') {
    // 对于最小值，高亮显示最小的
    return record[key] === minValue
  } else if (key === 'kurtosis' || key === 'skewness') {
    // 对于峰度和偏度，高亮显示绝对值最大的
    const absValues = allValues.map(v => Math.abs(v))
    const maxAbsValue = Math.max(...absValues.filter(v => v !== undefined && v !== null))
    return Math.abs(record[key]) === maxAbsValue
  } else {
    // 对于其他统计量，高亮显示最大的
    return record[key] === maxValue
  }
}

// 判断统计卡片是否需要高亮显示
const isStatHighlighted = (key: string): boolean => {
  if (!currentChannelData.value || !state.dataResult) return false
  
  // 获取所有通道的该统计量值
  const allValues = state.dataResult.map(channel => {
    if (channel.time_stats && channel.time_stats[0] && channel.time_stats[0][key] !== undefined) {
      return channel.time_stats[0][key]
    }
    return null
  }).filter(v => v !== null)
  
  // 当前通道的值
  const currentValue = currentChannelData.value.time_stats[0][key]
  if (currentValue === undefined) return false
  
  // 根据不同的统计量类型，决定高亮最大值还是最小值
  if (key === 'min') {
    // 对于最小值，高亮显示最小的
    return currentValue === Math.min(...allValues)
  } else if (key === 'kurtosis' || key === 'skewness') {
    // 对于峰度和偏度，高亮显示绝对值最大的
    const absValues = allValues.map(v => Math.abs(v as number))
    const maxAbsValue = Math.max(...absValues)
    return Math.abs(currentValue as number) === maxAbsValue
  } else {
    // 对于其他统计量，高亮显示最大的
    return currentValue === Math.max(...allValues)
  }
}

// 配置数据
const filterConfig = ref<FilterConfig | null>(null)
const calcConfig = ref<CalculationConfig | null>(null)
// const fftConfig = ref<FFTSettings | null>(null)

// 步骤组件引用
const filterStepRef = ref()
const calcStepRef = ref()
// const fftStepRef = ref()

// 开始配置流程
const startConfiguration = () => {
  currentStep.value = 1
  stepModalVisible.value = true
  filterConfig.value = null
  calcConfig.value = null
  // fftConfig.value = null
  stepsValid[0] = true
  stepsValid[1] = true
  stepsValid[2] = true
  stepsValid[3] = true
  // stepsValid[4] = true
}

// 处理步骤验证
const handleStepValid = (step: number, isValid: boolean) => {
  stepsValid[step] = isValid
}

// 下一步
const nextStep = async () => {
  // 在离开当前步骤前保存数据
  // 第一步也需要进行保存
  debugger
  if (currentStep.value === 2) {
    filterConfig.value = await filterStepRef.value.getConfig()
  } else if (currentStep.value === 3) {
    calcConfig.value = await calcStepRef.value.getConfig()
  }
  // } else if (currentStep.value === 3) {
  //   fftConfig.value = await fftStepRef.value.getConfig()
  // }
  currentStep.value++
}

// 上一步
const prevStep = () => {
  currentStep.value--
}

// 提交配置
const submitConfig = async () => {
  debugger
  loading.value = true
  try {
    // 获取最终配置
    const finalConfig = {
      filterConfig: filterConfig.value,
      calculationConfig: calcConfig.value,
      // fftConfig: fftConfig.value
    }
    const dataAnalysisReq = {
      dataUrl: state.dataUrl,
      ch_list: state.ch_list,
      time_span: state.time_span,
      // filterConfig
      lowcut: parseFloat(finalConfig.filterConfig?.fc1),
      highcut: parseFloat(finalConfig.filterConfig?.fc2),
      order: finalConfig.filterConfig?.order,
      filter_type: finalConfig.filterConfig?.filterType,
      filter_design: finalConfig.filterConfig?.prototype,
      ripple: parseFloat(finalConfig.filterConfig?.ripple),
      // calculationConfig
      block_size_sec: finalConfig.calculationConfig?.blockSize,
      overlap_percent: finalConfig.calculationConfig?.overlapValue,
      features: finalConfig.calculationConfig?.outputParams,
    }
    console.log('完整配置数据:', dataAnalysisReq)
    // 提交数据
    const dataAnalyRes = await dataReadAnalysisData(dataAnalysisReq)
    state.dataResult = JSON.parse(dataAnalyRes.data)
    console.log(state.dataResult)
    state.dataIsLoad = true
    Message.success('配置保存成功')
    // 关闭弹窗
    stepModalVisible.value = false
  } catch (error) {
    Message.error('配置保存失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 取消配置
const cancelConfig = () => {
  if (loading.value) return

  stepModalVisible.value = false
}

// 辅助函数 - 将数值转换为颜色
const getColorFromValue = (colorValue: number): string => {
  // 如果颜色值为0或未定义，返回默认颜色
  if (!colorValue) {
    return '#1890ff' // 默认蓝色
  }
  
  // 将数值转换为十六进制颜色
  try {
    // 假设colorValue是RGB值
    return `#${colorValue.toString(16).padStart(6, '0')}`
  } catch (e) {
    return '#1890ff' // 转换失败时返回默认颜色
  }
}

// 辅助函数 - 获取通道选项列表
const getChannelOptions = () => {
  if (!state.dataChInfo || !Array.isArray(state.dataChInfo)) {
    return []
  }
  
  return state.dataChInfo.map(channel => ({
    label: channel.name || `AI ${channel.index}`,
    value: channel.name || `AI ${channel.index}`
  }))
}

// 选择通道
const selectChannel = (channel: any) => {
  const channelName = channel.name || `AI ${channel.index}`
  
  // 检查通道是否已经被选中
  const channelIndex = state.ch_list.indexOf(channelName)
  
  if (channelIndex === -1) {
    // 如果通道未被选中，则添加到选中列表
    state.ch_list.push(channelName)
    Message.success(`已选择通道: ${channelName}`)
  } else {
    // 如果通道已被选中，则从选中列表中移除
    // 确保至少保留一个选中的通道
    if (state.ch_list.length > 1) {
      state.ch_list.splice(channelIndex, 1)
      Message.success(`已取消选择通道: ${channelName}`)
    } else {
      Message.warning('至少需要选择一个通道')
    }
  }
}

// 判断通道是否被选中
const isChannelSelected = (channel: any): boolean => {
  const channelName = channel.name || `AI ${channel.index}`
  return state.ch_list.includes(channelName)
}

// 上传
const handleUpload = (options: RequestOption) => {
  const controller = new AbortController()
    ; (async function requestWrap() {
      const { onProgress, onError, onSuccess, fileItem, name = 'file' } = options
      onProgress(20)
      const formData = new FormData()
      formData.append(name as string, fileItem.file as Blob)
      try {
        const dataRes = await uploadFile(formData)
        Message.success('上传成功')
        state.dataUrl = dataRes.data.url
        onSuccess(dataRes)
        // 加载通道列表
        const dataChRes = await dataReadGetDataChanelList(state.dataUrl)
        debugger
        state.dataChInfo = JSON.parse(dataChRes.data)
        // 初始化通道选择和时间区间
        if (state.dataChInfo && Array.isArray(state.dataChInfo) && state.dataChInfo.length > 0) {
          // 默认选择第一个通道
          state.ch_list = [state.dataChInfo[0].name || `AI ${state.dataChInfo[0].index}`]
          console.log(state.ch_list)
          // 时间区间保持默认值 [0, 0.1]
        }
      } catch (error) {
        onError(error)
        Message.error('加载数据通道信息失败: ' + (error as Error).message)
      }
    })()
  return {
    abort() {
      controller.abort()
    },
  }
}
</script>

<style scoped>
.highlight-value {
  color: #165DFF;
  font-weight: bold;
  background-color: rgba(22, 93, 255, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.stat-card {
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2px solid transparent;
}

.stat-card:hover {
  border-color: #165DFF;
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.15);
  transform: translateY(-2px);
}

.stat-card-highlight {
  border: 2px solid #165DFF;
  box-shadow: 0 2px 10px rgba(22, 93, 255, 0.2);
  transform: translateY(-2px);
}

.stat-card-highlight .stat-title {
  color: #165DFF;
  font-weight: bold;
}

.stat-card-highlight .stat-value {
  color: #165DFF;
}

.stat-card .stat-hint {
  opacity: 0.7;
  transition: opacity 0.3s ease;
}

.stat-card:hover .stat-hint {
  opacity: 1;
}
.data-analysis-page {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.data-analysis-header {
  flex-shrink: 0;
  margin-bottom: 20px;
}

.step-modal :deep(.arco-modal-body) {
  padding: 20px;
}

.step-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.steps {
  margin-bottom: 20px;
}

.step-content {
  flex: 1;
  min-height: 400px;
  padding: 10px;
}

.step-panel {
  height: 100%;
  overflow-y: auto;
}

.fft-step-panel {
  height: 600px;
  overflow-y: auto;
}

.step-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 数据通道信息展示样式 */
.data-channels-container {
  margin-top: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 16px;
  background-color: #fafafa;
  flex-shrink: 0;
}

.data-channels-container h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

.data-channels-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.channel-card {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s, border-left 0.2s;
  cursor: pointer;
  position: relative;
  border-left: 3px solid transparent;
}

.channel-card-selected {
  border-left: 3px solid #165dff;
  background-color: #f0f7ff;
}

.channel-card-selected::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 3px;
  height: 100%;
  background-color: #165dff;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { opacity: 0.6; }
  50% { opacity: 1; }
  100% { opacity: 0.6; }
}

.channel-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.channel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f0f2f5;
  border-bottom: 1px solid #e8e8e8;
}

.channel-index {
  font-weight: 600;
  color: #333;
}

.channel-color {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #d9d9d9;
}

.channel-content {
  padding: 12px 16px;
}

.form-row {
  display: flex;
  margin-bottom: 8px;
  align-items: center;
}

.form-row label {
  width: 80px;
  color: #666;
  font-size: 14px;
}

.form-row div {
  flex: 1;
  font-size: 14px;
  color: #333;
}

.loading-channels {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.no-data-message {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 14px;
}

/* 通道选择和时间区间样式 */
.channel-selection-container {
  margin-top: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 16px;
  background-color: #fafafa;
  flex-shrink: 0;
}

.channel-selection-container h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

.selection-section {
  background-color: white;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.time-range-inputs {
  display: flex;
  align-items: center;
  flex: 1;
}

.range-separator {
  margin: 0 8px;
  color: #666;
}

.unit-label {
  margin-left: 8px;
  color: #666;
}

/* 数据分析结果展示样式 */
.data-result-container {
  margin-top: 30px;
  padding: 24px;
  background-color: #f9fafc;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  overflow-y: auto;
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #eaedf1;
}

.result-title {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 20px;
  color: #333;
  font-weight: 600;
  display: flex;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.result-title::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 20px;
  background-color: #165dff;
  margin-right: 10px;
  border-radius: 2px;
}

.channel-selector {
  margin-bottom: 20px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 16px;
}

.channel-selector h3 {
  margin: 0 10px 0 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
  white-space: nowrap;
  display: flex;
  align-items: center;
}

.channel-selector h3::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #165dff;
  margin-right: 8px;
  border-radius: 2px;
}

.channel-selector h3 :deep(svg) {
  margin-right: 5px;
  color: #165dff;
}

.channel-selector :deep(.arco-select) {
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.channel-selector :deep(.arco-select:hover) {
  border-color: #165dff;
}

.result-content {
  margin-top: 20px;
  flex: 1;
  overflow-y: auto;
}

/* 统计数据展示样式 */
.stats-container {
  margin-bottom: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  background-color: white;
  padding: 16px;
}

.stats-container h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.stats-container h3::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #165dff;
  margin-right: 8px;
  border-radius: 2px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 10px;
}

.stat-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  text-align: center;
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border-left: 3px solid transparent;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 140px;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 16px rgba(22, 93, 255, 0.15);
  border-left: 3px solid #165dff;
  background-color: #f0f7ff;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.7s;
}

.stat-card:hover::before {
  left: 100%;
}

.stat-card::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background: linear-gradient(90deg, #165dff, #36f, #165dff);
  transform: scaleX(0);
  transform-origin: left;
  transition: transform 0.3s ease-out;
}

.stat-card:hover::after {
  transform: scaleX(1);
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #165dff;
  margin-bottom: 4px;
  line-height: 1.2;
  word-break: break-all;
  max-height: 48px;
  overflow: hidden;
}

.stat-unit {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
  background-color: #f0f7ff;
  display: inline-block;
  padding: 2px 6px;
  border-radius: 12px;
  margin-top: 4px;
}

.stat-hint {
  font-size: 12px;
  color: #165dff;
  opacity: 0.7;
  border-top: 1px dashed #e8e8e8;
  padding-top: 6px;
  margin-top: 6px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-hint::before {
  content: '🔍';
  margin-right: 4px;
  font-size: 12px;
}

.stat-card:hover .stat-hint {
  opacity: 1;
  background-color: rgba(22, 93, 255, 0.1);
  border-radius: 4px;
}

/* 特征数据表格样式 */
.features-container {
  margin-bottom: 30px;
  max-height: 400px;
  overflow-y: auto;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  background-color: white;
  padding: 16px;
}

.features-container h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.features-container h3::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #165dff;
  margin-right: 8px;
  border-radius: 2px;
}

.features-container :deep(.arco-table-th) {
  background-color: #f0f7ff;
  color: #165dff;
  font-weight: 500;
}

.features-container :deep(.arco-table-tr:hover) {
  background-color: rgba(22, 93, 255, 0.05);
}

.features-container :deep(.arco-table-td) {
  color: #333;
}

/* 结果图片展示样式 */
.result-images {
  margin-bottom: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  background-color: white;
  padding: 16px;
}

.result-images h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.result-images h3::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #165dff;
  margin-right: 8px;
  border-radius: 2px;
}

.image-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  max-height: 600px;
  overflow-y: auto;
  padding-right: 10px;
}

.image-container {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 3px 12px rgba(0, 0, 0, 0.12);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  background-color: white;
  transition: transform 0.3s, box-shadow 0.3s;
}

.image-container:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}

.image-title {
  padding: 12px 16px 8px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  background-color: #f9f9f9;
  border-bottom: 1px solid #eee;
}

.image-description {
  padding: 8px 16px 12px;
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
}

.result-image {
  width: 100%;
  height: 220px;
  object-fit: contain;
  transition: transform 0.3s;
  padding: 8px;
  background-color: white;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  z-index: 2;
}

.image-overlay span {
  color: white;
  font-size: 15px;
  font-weight: 500;
  padding: 10px 20px;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transform: translateY(0);
  transition: transform 0.3s, box-shadow 0.3s;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.image-container:hover .image-overlay span {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.image-container:hover .result-image {
  transform: scale(1.05);
}

/* 图片预览弹窗样式 */
.image-preview-modal :deep(.arco-modal-body) {
  padding: 0;
}

.preview-container {
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  min-height: 400px;
  max-height: 80vh;
  position: relative;
}

.preview-image {
  max-width: 100%;
  max-height: 65vh;
  object-fit: contain;
  margin: 0 auto;
  display: block;
}

.preview-title {
  color: #000000;
  font-size: 18px;
  font-weight: 600;
  text-align: center;
  padding: 16px 24px 8px;
  background-color: rgba(255, 255, 255, 0.8);
  margin: 0;
}

.preview-description {
  color: #000000;
  font-size: 14px;
  line-height: 1.5;
  text-align: center;
  padding: 8px 24px 16px;
  background-color: rgba(255, 255, 255, 0.8);
  margin: 0;
  max-width: 800px;
  margin: 0 auto;
}

.preview-navigation {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-top: 1px solid #eee;
}

.preview-counter {
  margin: 0 16px;
  font-size: 14px;
  color: #666;
}
</style>